<?php
/**
 * Created by PhpStorm.
 * User: mr2longly <mr2longly@gmail.com>
 * Date: 7/9/16
 * Time: 00:19
 */

namespace Home\Model;


use Common\Library\BusinessException;
use Common\Library\Constant;

use Think\Log;
use Think\Model;

class MerchantModel {

    public function getNearByList($lat, $lng, array $where = [])
    {
        $whereStr = 'true';
        if ($where) {
            foreach ($where as $_field => $_val) {
                $whereStr .= " AND {$_field} = {$_val}";
            }
        }

        $sql = sprintf(
            'SELECT *,
            (
                %d * acos
                (
                    cos( radians(%.6f) ) *
                    cos( radians(lat) ) *
                    cos( radians(lng) - radians(%.6f) ) +
                    sin( radians(%.6f) ) *
                    sin( radians(lat) )
                )
            ) AS distance
            FROM merchant WHERE %s
            HAVING distance < %d ORDER BY distance;',
            Constant::EARTH_RADIUS, $lat, $lng, $lat, $whereStr, Constant::NEARBY_DISTANCE
        );

        $merchantList = M()->query($sql);
        if ($merchantList) {
            foreach ($merchantList as &$merchant) {
                $merchant['distance'] = round($merchant['distance'], 1);
                $merchant['create_time'] = date('Y-m-d H:i:s', $merchant['add_time']);
                if(date('Y-m-d', $merchant['add_time']) < '2016-12-30'){
                    $merchant['logo'] = empty($merchant['logo']) ? '' : C('ADMIN_SERVER_HOST') . $merchant['logo'];
                }else{
                    $merchant['logo'] = empty($merchant['logo']) ? '' : C('IMAGE_PATH') . $merchant['logo'];
                }

                // 处理优惠信息
                $this->_processPromotion($merchant);

                unset($merchant['images'], $merchant['add_time']);
            }

            unset($merchant);
        }

        return $merchantList && is_array($merchantList) ? $merchantList : [];
    }

    private function _processPromotion(&$merchant)
    {
        $title = '';
        if (isset($merchant['discount_first_order']) && ($reduce_1st = (int)$merchant['discount_first_order'])) {
            //$title .= '首单最高减免' . fen2yuan($reduce_1st) . '元';
            $title .= '首单最高减免50元';
        }

        if (isset($merchant['discount_full_amount'], $merchant['discount_full_reduce'])) {
            $discountFullAmount   = fen2yuan((int)$merchant['discount_full_amount']);
            $discountReduceAmount = fen2yuan((int)$merchant['discount_full_reduce']);

            if ($discountFullAmount && $discountReduceAmount) {
                if ($title) {
                    $title .= '另满' . $discountFullAmount . '减' . $discountReduceAmount;
                } else {
                    $title .= '满' . $discountFullAmount . '减' . $discountReduceAmount;
                }
            }
        }

        if ($title) {
            $merchant['promotion'] = [
                'title' => $title,
                'icon' => C('ADMIN_SERVER_HOST') . '/data/upload/icon/icon-jian.png',
            ];
        }
    }
    public function has($data, $throwException = true) {
        if (is_numeric($data)) {
            $data = ['id' => $data];
        }

        if (!is_array($data)) {
            if ($throwException) {
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }
            return null;
        }

        $information = M('Merchant')->where($data)->find();

        if (!$information) {
            $throwException && BusinessException::throwException(Constant::MERCHANT_NOT_FOUND);
        }

        return $information;
    }

    public function getTermsList($name = NULL, $level = NULL){
        if($name){
            $position = M('position_'.$level)->where([$level.'_name'=> $name])->find();
            if($position){
                $city_id = $position[$level.'_id'];
            }else{
                return false;
            }
        }else{
            $city_id = 1;
        }

        $sql = 'SELECT t.term_id as type_id, name as type_name, CONCAT(t.image_path, t.image_name) as type_img FROM admin_terms t
                LEFT JOIN admin_term_city c ON t.term_id = c.term_id
                WHERE c.city_id = '.$city_id.' ORDER BY c.listorder';
        $result = M()->query($sql);
        if($result){
            return $result;
        }else{
            return false;
        }
    }
    /***************************************
     *获取商户佣金列表   getCommissionList
     ***************************************/
    public function getCommissionList($merchantId,$offset,$length,$date_time,$type)
    {
        $date_time1 = ($date_time != '' && $date_time != 0) ? $date_time : date("Y-m");//时间限制
        $december = strtotime('2016-12-01 00:00:00');//十二月1号 00:00:00 (十二月之前的单子不计入)
        $time = time();//当前时间戳

        $sql = "SELECT * FROM  merchant WHERE id = " . $merchantId;
        $commission_arrdata1 = M()->query($sql);
        $deduct_money = $commission_arrdata1[0]['deduct_money'];//是否支持逾期佣金扣款
        $commission_arr = [];
        $sql = "SELECT consume_history.discount_interest,consume_history.id as consume_id,c.real_name as customer_name,consume_history.add_time, FROM_UNIXTIME(consume_history.add_time, \"%Y-%m-%d %H:%i:%S\") as consume_time,consume_history.commission_add,consume_history.amount as consume_amount,m.commision_balance,consume_history.plan_id FROM consume_history LEFT JOIN customer c on c.id=consume_history.customer_id LEFT JOIN merchant_user m on m.merchant_id=consume_history.merchant_id WHERE consume_history.merchant_id = " . $merchantId . " AND consume_history.type = 2 AND consume_history.status IN (1,3) AND consume_history.add_time >= " . strtotime($date_time1 . '-01 -1 months') . " AND consume_history.add_time >=" . $december . " AND consume_history.add_time < " . strtotime($date_time1 . '-01 +2 months') . "  ORDER BY consume_history.id DESC  LIMIT " . $offset . ',' . $length;
       // $sql = "SELECT consume_history.discount_interest,consume_history.id as consume_id,c.real_name as customer_name,consume_history.add_time, FROM_UNIXTIME(consume_history.add_time, \"%Y-%m-%d %H:%i:%S\") as consume_time,consume_history.commission_add,consume_history.amount as consume_amount,m.commision_balance,consume_history.plan_id FROM consume_history LEFT JOIN customer c on c.id=consume_history.customer_id LEFT JOIN merchant_user m on m.merchant_id=consume_history.merchant_id WHERE consume_history.merchant_id = " . $merchantId . " AND consume_history.type = 2 AND consume_history.status IN (1,3) AND consume_history.add_time >= " . strtotime($date_time1 . '-01 -1 months') . " AND  consume_history.add_time < " . strtotime($date_time1 . '-01 +2 months') . "  ORDER BY consume_history.id DESC  LIMIT " . $offset . ',' . $length;

        if ($date_time == '' && $type == 0) {
            $sql = "SELECT consume_history.discount_interest,consume_history.id as consume_id,c.real_name as customer_name,consume_history.add_time, FROM_UNIXTIME(consume_history.add_time, \"%Y-%m-%d %H:%i:%S\") as consume_time,consume_history.commission_add,consume_history.amount as consume_amount,m.commision_balance,consume_history.plan_id FROM consume_history LEFT JOIN customer c on c.id=consume_history.customer_id LEFT JOIN merchant_user m on m.merchant_id=consume_history.merchant_id WHERE consume_history.merchant_id = " . $merchantId . " AND consume_history.type = 2 AND consume_history.status IN (1,3) AND consume_history.add_time >=" . $december . " AND consume_history.commission_add = 0  ORDER BY consume_history.id DESC  LIMIT " . $offset . ',' . $length;
          //  $sql = "SELECT consume_history.discount_interest,consume_history.id as consume_id,c.real_name as customer_name,consume_history.add_time, FROM_UNIXTIME(consume_history.add_time, \"%Y-%m-%d %H:%i:%S\") as consume_time,consume_history.commission_add,consume_history.amount as consume_amount,m.commision_balance,consume_history.plan_id FROM consume_history LEFT JOIN customer c on c.id=consume_history.customer_id LEFT JOIN merchant_user m on m.merchant_id=consume_history.merchant_id WHERE  consume_history.type = 2 AND consume_history.status IN (1,3) AND consume_history.commission_add = 0  ORDER BY consume_history.id DESC  LIMIT " . $offset . ',' . $length;
        }
        $history1 = M()->query($sql);
        Log::write("获取商户佣金列表history" . json_encode($history1) . '长度' . count($history1), Log::DEBUG);
        if ($date_time == '' && $type == 0) {//总账单显示
            if (count($history1)) {
                foreach ($history1 as $kk => $va) {
                    $commision_all = 0;
                    $rebate_arr = $this->getRebate($merchantId, $va['consume_id']);
                    $rebate_first = $rebate_arr['rebate_first'];//时时返点
                    $rebate_last = $rebate_arr['rebate_last'];//次次月返点
                    $rebate_spare = $rebate_arr['rebate_spare'];//不达标时返点
                    $detail = M('ConsumeInstallmentHistory')->order('id')->where(['parent_id' => $va['consume_id']])->
                    field('repayment_time, status,add_time, update_time')->limit(1)->find();

                    $next1_month = date('Y-m-01', strtotime("+2 months", $va['add_time']));//下单的次次月月初
                    Log::write("添加时间".date('Y-m-01',$va['add_time'])."次次月初".$next1_month,Log::DEBUG);
                    $next_one = strtotime(date('Y-m-01', strtotime("+1 months", $va['add_time'])));//次月一号 00:00:00
                    $this_one = strtotime(date('Y-m-01', $va['add_time']));//下单当月一号

                    if ($time >= strtotime($next1_month)) {//下单的次次月月初   清算下单当月业绩
                        $performance_liji = $this->getSalesLow($merchantId, $next_one);//当月最低业绩
                        $performance = $this->getPerformance($this_one, $next_one, $merchantId);
                        if ($detail['status'] == 1) {//已还款
                            if ($detail['update_time'] <= $detail['repayment_time']) {//未逾期
                                if ($va['commission_add'] == 0) {
                                    if ($va['discount_interest'] != 2) {//优惠单不计返利
                                        if ($performance < $performance_liji) {//不达标
                                            $commision_all += ceil($va['consume_amount'] * $rebate_spare);
                                        } else {
                                            $commision_all += ceil($va['consume_amount'] * $rebate_last);
                                        }
                                    }
                                    M()->query("UPDATE consume_history SET commission_add = 1 WHERE id = " . $va['consume_id']);
                                }
                            } else {//逾期
                                if ($va['commission_add'] == 0) {
                                    if ($va['discount_interest'] == 2) {
                                        $commision_all += 0;
                                    } else {
                                        if ($deduct_money == 1) {//支持逾期订单扣除已经给的返点
                                            $commision_all -= ceil($va['consume_amount'] * $rebate_first);
                                        } elseif ($deduct_money == 0) {//不支持逾期订单扣除已经给的返点
                                            $commision_all -= 0;
                                        }
                                    }
                                    M()->query("UPDATE consume_history SET commission_add = 1 WHERE id = " . $va['consume_id']);
                                }
                            }
                        } else {//未还
                            if ($va['commission_add'] == 0) {
                                if ($va['discount_interest'] == 2) {
                                    $commision_all += 0;
                                } else {
                                    if ($deduct_money == 1) {
                                        $commision_all -= ceil($va['consume_amount'] * $rebate_first);
                                    } elseif ($deduct_money == 0) {
                                        $commision_all -= 0;
                                    }
                                }
                                M()->query("UPDATE consume_history SET commission_add = 1 WHERE id = " . $va['consume_id']);
                            }
                        }

                        if ($commision_all != 0) {
                            M()->query("UPDATE merchant_user SET commision_balance = commision_balance + $commision_all WHERE merchant_id = '$merchantId'");
                        }
                    }
                }
            }
            $arr = M()->query("SELECT * FROM merchant_user  WHERE merchant_id = '$merchantId'");
            $commission_arr['commision_all'] = $arr[0]['commision_balance'];
            return $commission_arr;
        }
        else {//每月佣金列表
            $start = strtotime($date_time1 . '-01');//本月一号 00:00:00
            $end = strtotime($date_time1 . '-01 +1 months');//下月一号 00:00:00
            $per_month = strtotime($date_time1 . '-01 -1 months');//上月一号 00:00:00
            $next_month = strtotime($date_time1 . '-01 +2 months');//下月月底 00:00:00

            $performance_liji = $this->getSalesLow($merchantId, $end);//当月最低业绩
            $performance_pre = $this->getSalesLow($merchantId, $start);//上一个月最低业绩
            $performance_next = $this->getSalesLow($merchantId, $next_month);//次月最低业绩
            $commission_get = $commission_fine =  0;
            $commission_get_pre = $commission_fine_pre = 0;
            $commission_get_next = $commission_fine_next = 0;
            $arr_get = $arr_fine = [];
            foreach ($history1 as $k => $v) {
                $rebate_arr = $this->getRebate($merchantId, $v['consume_id']);
                $rebate_first = $rebate_arr['rebate_first'];//时时返点
                $rebate_last = $rebate_arr['rebate_last'];//次次月返点
                $rebate_spare = $rebate_arr['rebate_spare'];//不达标时返点
                Log::write('时时返点利率' . $rebate_first . "次次月返点利率" . $rebate_last . '不达标利率' . $rebate_spare, Log::DEBUG);

                $detail = M('ConsumeInstallmentHistory')->order('id')->where(['parent_id' => $v['consume_id']])->
                field('repayment_time,status,update_time,add_time')->limit(1)->find();
                if ($detail['status'] == 1 && $detail['repayment_time'] >= $detail['update_time']) {//已还  未逾期
                    $arr_get[$k] = $v;
                }
                elseif ($detail['status'] == 0 && $detail['repayment_time'] < strtotime("+1 months +1 day", $detail['add_time']) && $detail['update_time'] == 0) {//未还  未逾期
                    $arr_get[$k] = $v;
                }
                else {
                    $arr_fine[$k] = $v;
                    if ($v['add_time'] >= $per_month && $v['add_time'] < $start && $v['discount_interest'] !=2) {
                        if($deduct_money==0 ){
                            $commission_fine_pre += 0;
                        }else{
                            $commission_fine_pre += $v['consume_amount'] * $rebate_first;
                        }
                    } elseif ($v['add_time'] >= $start && $v['add_time'] < $end && $v['discount_interest'] !=2) {

                        if($deduct_money==0){
                            $commission_fine += 0;
                        }else{
                            $commission_fine += $v['consume_amount'] * $rebate_first;
                        }
                    } elseif ($v['add_time'] >= $end && $v['add_time'] < $next_month && $v['discount_interest'] !=2) {
                        if($deduct_money==0 ){
                            $commission_fine_next += 0;
                        }else{
                            $commission_fine_next += $v['consume_amount'] * $rebate_first;
                        }
                    }
                }
                if ($v['add_time'] >= $per_month && $v['add_time'] < $start) {
                    $performance_0 = $this->getPerformance($per_month, $start, $merchantId);
                } elseif ($v['add_time'] >= $start && $v['add_time'] < $end) {
                    $performance_now = $this->getPerformance($start, $end, $merchantId);
                } elseif ($v['add_time'] >= $end && $v['add_time'] < $next_month) {
                    $performance_1 = $this->getPerformance($end, $next_month,$merchantId);
                }
            }
            Log::write('下单当月业绩' . $performance_now."是否优惠：".$v['discount_interest'], Log::DEBUG);
            Log::write('最低标准' . $performance_liji, Log::DEBUG);
            if ($type == 1) {//未逾期订单
                $history = $arr_get;
            } elseif ($type == 2) {//逾期订单
                $history = $arr_fine;
            } else {
                $history = $history1;
            }
            Log::write("最后的history" . json_encode($history) . '长度' . count($history), Log::DEBUG);
            Log::write("未逾期订单" . json_encode($arr_get) . '长度' . count($arr_get), Log::DEBUG);
            Log::write("逾期订单" . json_encode($arr_fine) . '长度' . count($arr_fine), Log::DEBUG);

            if (count($history)) {
                foreach ($history as $k => $v) {
                    $rebate_arr = $this->getRebate($merchantId, $v['consume_id']);
                    $rebate_first = $rebate_arr['rebate_first'];//时时返点
                    $rebate_last = $rebate_arr['rebate_last'];//次次月返点
                    $rebate_spare = $rebate_arr['rebate_spare'];//不达标时返点
                    $detail = M('ConsumeInstallmentHistory')->order('id')->where(['parent_id' => $v['consume_id']])->
                    field('overdue_amount, amount, repayment_time, discount_rebate,FROM_UNIXTIME(repayment_time, "%Y-%m-%d") AS repay_date, status,add_time, update_time')->limit(1)->find();
                    Log::write("小单detail" . json_encode($detail), Log::DEBUG);

                    if ($v['add_time'] >= $per_month && $v['add_time'] < $start) {//上月
                        if ($time >= $end) {
                            if ($detail['status'] == 1) {//已还款
                                if ($performance_0 < $performance_pre) {//不达标
                                    $commission_get_pre += $v['consume_amount'] * ($rebate_first + $rebate_spare);
                                } else {
                                    $commission_get_pre += $v['consume_amount'] * ($rebate_first + $rebate_last);
                                }
                            }
                        }
                    }
                    elseif ($v['add_time'] >= $start && $v['add_time'] < $end) {//当月
                        $next1_month = date('Y-m-01', strtotime("+2 months", $v['add_time']));//下单的次次月月初
                        if ($time >= $next_month) {//下单的次次月月初   清算下单当月业绩 并且下单日期在12月1号00:00:00 之后
                            if ($detail['status'] == 1) {//已还款
                                if ($detail['update_time'] <= $detail['repayment_time']) {//未逾期
                                    if($v['discount_interest'] !=2) {
                                        if ($performance_now < $performance_liji) {//不达标
                                            $commission_get += $v['consume_amount'] * ($rebate_first + $rebate_spare);
                                        } else {
                                            $commission_get += $v['consume_amount'] * ($rebate_first + $rebate_last);
                                        }
                                    }
                                    $status = 1;

                                } else {//逾期
                                    $status = 3;
                                    if($deduct_money==0 && $v['discount_interest'] !=2){
                                        $commission_get += $v['consume_amount'] * $rebate_first;
                                    }
                                }
                            } else {//未还
                                $status = 3;
                                if($deduct_money==0 && $v['discount_interest'] !=2){
                                    $commission_get += $v['consume_amount'] * $rebate_first;
                                }
                            }
                            if($v['discount_interest'] == 2 && $type==0){
                                $commission_arr['commision_list'][] = array('customer_name' => $v['customer_name'], 'consume_date' => $v['consume_time'],'commission_arrive'=>'0', 'commision_stages' => array(
                                  //  '0' => array('name' => '已到账佣金', 'money' => '￥' . (0) , 'status' => 0),
                                    '0' => array('time' => date("Y-m-d", $v['add_time']), 'money' => '￥' . (0) , 'status' => '4')));

                            }else {
                                if ($status != 3 && $v['discount_interest'] != 2) {
                                    if ($performance_now >= $performance_liji) {//达标
                                        $commission_arr['commision_list'][] = array('customer_name' => $v['customer_name'], 'consume_date' => $v['consume_time'], 'commission_arrive'=>(ceil($v['consume_amount'] * ($rebate_first + $rebate_last))), 'commision_stages' => array(
                                          //  '0' => array('name' => '已到账佣金', 'money' => '￥' . (ceil($v['consume_amount'] * ($rebate_first + $rebate_last)) / 100) , 'status' => 0),
                                            '0' => array('time' => date("Y-m-d", $v['add_time']), 'money' => '￥' . (ceil($v['consume_amount'] * $rebate_first) / 100) , 'status' => '0'),
                                            '1' => array('time' => $next1_month, 'money' => '￥' . (ceil($v['consume_amount'] * $rebate_last) / 100) , 'status' => '1')));
                                    } elseif ($performance_now < $performance_liji) {// 不达标
                                        $commission_arr['commision_list'][] = array('customer_name' => $v['customer_name'], 'consume_date' => $v['consume_time'], 'commission_arrive'=>(ceil($v['consume_amount'] * ($rebate_first + $rebate_spare))),'commision_stages' => array(
                                        //    '0' => array('name' => '已到账佣金', 'money' => '￥' . (ceil($v['consume_amount'] * ($rebate_first + $rebate_spare)) / 100) , 'status' => 0),
                                            '0' => array('time' => date("Y-m-d", $v['add_time']), 'money' => '￥' . (ceil($v['consume_amount'] * $rebate_first) / 100) , 'status' => '0'),
                                            '1' => array('time' => $next1_month, 'money' => '￥' . (ceil($v['consume_amount'] * $rebate_spare) / 100) , 'status' => '2')));
                                    }
                                } elseif ($status == 3 && $v['discount_interest'] != 2) {//逾期
                                    if ($deduct_money == 1) {//支持逾期扣除佣金
                                        $commission_arr['commision_list'][] = array('customer_name' => $v['customer_name'], 'consume_date' => $v['consume_time'],'commission_arrive'=>'0', 'commision_stages' => array(
                                            '0' => array('time' => $next1_month, 'money' => '￥' . (0) , 'status' => '3'),
                                         //   '1' => array('name' => date("Y-m-d", $v['add_time']), 'money' => '￥' . (ceil($v['consume_amount'] * $rebate_first) / 100), 'status' => '1'),
                                          //  '2' => array('name' => $next1_month, 'money' => '￥' . (-ceil($v['consume_amount'] * $rebate_first) / 100), 'status' => '3')
                                        ));
                                    } elseif ($deduct_money == 0) {
                                        $commission_arr['commision_list'][] = array('customer_name' => $v['customer_name'], 'consume_date' => $v['consume_time'], 'commission_arrive'=>(ceil($v['consume_amount'] * $rebate_first)),'commision_stages' => array(
                                            '0' => array('time' => date("Y-m-d", $v['add_time']), 'money' => '￥' . (ceil($v['consume_amount'] * $rebate_first) / 100) , 'status' => '3'),
                                           // '1' => array('name' => date("Y-m-d", $v['add_time']), 'money' => '￥' . (ceil($v['consume_amount'] * $rebate_first) / 100) , 'status' => '1'),
                                          //  '2' => array('name' => $next1_month, 'money' => '￥' . (0), 'status' => '3')
                                        ));
                                    }
                                }
                            }

                        } else {//未到次次月初
                            if ($v['discount_interest'] != 2) {
                                $commission_get += $v['consume_amount'] * $rebate_first;
                            }
                            if ($v['add_time'] >= $start && $v['add_time'] < $end) {//下单当月
                                if($v['discount_interest'] == 2 && $type==0){//优惠单
                                    $commission_arr['commision_list'][] = array('customer_name' => $v['customer_name'], 'consume_date' => $v['consume_time'], 'commission_arrive'=>'0','commision_stages' => array(
                                        '0' => array('time' => date("Y-m-d", $v['add_time']), 'money' => '￥' . (0) , 'status' => '4'),
                                      //  '1' => array('time' => date("Y-m-d", $v['add_time']), 'money' => '0', 'status' => '4')
                                ));

                                }elseif ($v['discount_interest'] != 2) {//非优惠单
                                    $commission_arr['commision_list'][] = array('customer_name' => $v['customer_name'], 'consume_date' => $v['consume_time'], 'commission_arrive'=> ceil($v['consume_amount'] * $rebate_first),'commission_arrive'=>(ceil($v['consume_amount'] * $rebate_first)),'commision_stages' => array(
                                        //'0' => array('name' => '已到账佣金', 'money' => '￥' . (ceil($v['consume_amount'] * $rebate_first) / 100) , 'status' => 0),
                                        '0' => array('time' => date("Y-m-d", $v['add_time']), 'money' => '￥' . (ceil($v['consume_amount'] * $rebate_first) / 100) , 'status' => '0'),
                                    ));
                                }
                            }
                        }
                    } elseif ($v['add_time'] >= $end && $v['add_time'] < $next_month) {//次月
                        $last_time = strtotime("+2 months ", $next_month);
                        if ($time >= $last_time) {
                            if ($detail['status'] == 1) {//已还款
                                if ($performance_1 < $performance_next) {//不达标
                                    $commission_get_next += $v['consume_amount'] * ($rebate_first + $rebate_spare);
                                } else {
                                    $commission_get_next += $v['consume_amount'] * ($rebate_first + $rebate_last);
                                }
                            }
                        }
                    }

                }
                $arr = M()->query("SELECT * FROM merchant_user  WHERE merchant_id = '$merchantId'");
                $commission_arr['commision_all'] = $arr[0]['commision_balance'];
                $commission_arr['date_time'] = $date_time1;
                $commission_arr['commission_total'] = ceil($commission_get) + ceil($commission_fine);
                $commission_arr['commission_get'] = ceil($commission_get);
                $commission_arr['commission_fine'] = ceil($commission_fine);
                $commission_arr['pre_commission'] = ceil($commission_fine_pre) + ceil($commission_get_pre);
                $commission_arr['next_commission'] = ceil($commission_fine_next) + ceil($commission_get_next);
            } else {//history为空
                $commission_arr = $history;
                $arr = M()->query("SELECT * FROM merchant_user  WHERE merchant_id = '$merchantId'");
                $commission_arr['commision_all'] = $arr[0]['commision_balance'];
                $commission_arr['date_time'] = $date_time1;
                $commission_arr['commission_total'] = ceil($commission_get) + ceil($commission_fine);
                $commission_arr['commission_get'] = ceil($commission_get);
                $commission_arr['commission_fine'] = ceil($commission_fine);
                $commission_arr['pre_commission'] = ceil($commission_fine_pre) + ceil($commission_get_pre);
                $commission_arr['next_commission'] = ceil($commission_fine_next) + ceil($commission_get_next);
            }
            return $commission_arr;
        }
    }    

 ///计算商户业绩（每月）
    public function getPerformance($start,$end,$merchantId){

        $arr_all = M()->query("SELECT h.id,h.discount_interest,h.amount as consume_amount FROM consume_history h  WHERE h.merchant_id = ". $merchantId . ' AND h.type = 2 AND h.status in (1,3)  AND h.add_time >='.$start." AND h.add_time <".$end);

        $performance = 0;
        foreach ($arr_all as $k=>$v) {
            $detail = M('ConsumeInstallmentHistory')->order('id')->where(['parent_id' => $v['id']])->
            field('repayment_time,status,update_time,DATEDIFF(FROM_UNIXTIME(repayment_time,"%Y-%m-%d"), CURDATE()) AS fine_date')->limit(1)->find();
            Log::write("优惠类型：".$v['discount_interest'],Log::DEBUG);
            if (time() >= $end) {
                if ($v['discount_interest'] == 2) {
                    if(($detail['status'] == 0 && $detail['fine_date'][0] == '-') || ($detail['status'] == 1 && $detail['update_time'] > $detail['repayment_time'])) {
                        $limit = 1;
                    }else{
                        $limit = 0;
                    }
                    Log::write("优惠逾期：".$limit.",本单借款：".$v['consume_amount'],Log::DEBUG);
                    if ($limit==1) {
                        $performance += 0;
                    } else {
                        $performance += $v['consume_amount'];
                    }
                } else {
                    $performance += $v['consume_amount'];
                }
            }
        }
        Log::write("业绩结果：".$performance,Log::DEBUG);
        return $performance;
    }

    /////获取商户最低业绩（每月）
    public function getSalesLow($merchantId,$time){
        $sql = "SELECT * FROM merchant_commission_order WHERE addtime < ".$time." AND merchant_id = ".$merchantId;
        $per = M()->query($sql);
        $sales_low =$per[0]['sales_low'];//最低业绩
        return $sales_low;
    }
   ///获取返点
    public function getRebate($merchantId,$consume_id){
        $sql = "SELECT * FROM merchant_commission_order WHERE history_id = ".$consume_id." AND merchant_id = ".$merchantId;
        Log::write('利率'.$sql,Log::DEBUG);
        $rebate_arr = M()->query($sql);
        $rebate_arr = $rebate_arr[0];
        return $rebate_arr;

    }


}
